﻿using Fur.DatabaseAccessor;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace China.Core
{
    /// <summary>
    /// 用户表
    /// </summary>
    public class User : EntityBase, IEntityTypeBuilder<User>, IEntitySeedData<User>
    {
        /// <summary>
        /// 账户
        /// </summary>
        [Required, StringLength(32)]
        public string Account { get; set; }

        /// <summary>
        /// 密码
        /// </summary>
        [Required, StringLength(16)]
        public string Password { get; set; }

        /// <summary>
        /// 用户的角色，多对多的关系
        /// </summary>
        public ICollection<Role> Roles { get; set; }

        /// <summary>
        /// 关联关系表
        /// </summary>
        public List<UserRole> UserRoles { get; set; }

        public void Configure(EntityTypeBuilder<User> entityBuilder, DbContext dbContext, Type dbContextLocator)
        {
            entityBuilder.HasMany(u => u.Roles)
                .WithMany(u => u.Users)
                .UsingEntity<UserRole>(
                    u => u.HasOne(c => c.Role).WithMany(c => c.UserRoles).HasForeignKey(c => c.RoleId),
                    u => u.HasOne(c => c.User).WithMany(c => c.UserRoles).HasForeignKey(c => c.UserId),
                    u =>
                    {
                        u.HasKey(c => new { c.UserId, c.RoleId });
                        u.HasData(new { UserId = 1, RoleId = 1 });
                    });
        }

        /// <summary>
        /// 创建初始化数据
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="dbContextLocator"></param>
        /// <returns></returns>
        public IEnumerable<User> HasData(DbContext dbContext, Type dbContextLocator)
        {
            return new[]
            {
                new User
                {
                    Id=1, Account="admin", Password="admin"
                },
                new User
                {
                    Id=2, Account="dev", Password="dev123"
                }
            };
        }
    }
}
